#!/usr/bin/perl
use strict; use warnings;

use lib 'lib';

use Template;
use Template::Stash;

BEGIN {
    $Template::Stash::HASH_OPS->{ keyword_order } = sub {
        my $hash   = shift;
        my @sorted = sort { $a->{ sort_order } <=> $b->{ sort_order } }
                     values %{ $hash };

        return \@sorted;
    };

    $Template::Stash::SCALAR_OPS->{ clean_descr } = sub {
        my $descr        = shift;
        my $keyword      = shift || '';
        my $extra_spaces = shift || 0;
        my $second_line_indent = ' ' x ( $extra_spaces + length $keyword );

        if ( $extra_spaces ) {
            $descr =~ s{<pre>([^<]+)</pre>}
                       {_commify( $1 )}eg;
        }
        else {
            $descr =~ s{<pre>([^<]+)</pre>}
                       {_indent( $1 )}eg;
        }

        $descr =~ s{<br\s*/>}{\n$second_line_indent}g;

        return $descr;
    };

    $Template::Stash::HASH_OPS->{ commify } = sub {
        my $type_hash = shift;
        my @types     = sort keys %{ $type_hash };
        my $types;

        if ( @types == 1 ) {
            $types = "@types";
        }
        if ( @types == 2 ) {
            $types = join ' and ', @types;
        }
        else {
            $types = join ', ', @types;
            $types =~ s/, ([^,]+)$/, and $1/;
        }

        return $types;
    };
}

use Bigtop::Keywords;

my $template = shift || die "usage: $0 template\n";
my @doc_hash_categories;
my $urgencies = {
     1 => 'only occasionally used',
     3 => 'frequently used',
     5 => 'virtually required',
    10 => 'required',
};

my $tt = Template->new(
    {
        INCLUDE_PATH => [ qw( . skip ) ],
    }
);

$tt->process(
    $template,
    {
        categories => Bigtop::Keywords->get_full_doc_hash(),
        urgencies  => $urgencies,
        now        => scalar localtime,
    }
);

sub _indent {
    my $to_be_indented = shift;

    $to_be_indented    =~ s/^/    /gm;

    return "\n\n$to_be_indented\n";
}

sub _commify {
    my $to_be_commified = shift;

    my @pieces = split /\s+/, $to_be_commified;

    return join ', ', @pieces;
}

=head1 NAME

keywords - builds various ouput styles from keywords in Bigtop::Keywords

=head1 SYNOPSIS

    skip/keywords podsyntax.tt > lib/Bigtop/Docs/FullKeywords.pod
    skip/keywords quickpodsyntax.tt > lib/Bigtop/Docs/QuickKeywords.pod

=head1 DESCRIPTION

This script pulls docs from L<Bigtop::Keywords> and spits
to standard out.  What the output looks like depends on the template name
you supply on the command line.

=head1 AUTHOR

Phil Crow E<lt>crow.phil@gmail.comE<gt>

=head1 COPYRIGHT and LICENSE

Copyright (C) 2006-7 by Phil Crow

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.6 or,
at your option, any later version of Perl 5 you may have available.

=head1 POD Note

The rest of the POD below is really the template for the AutoKeywords file.

=cut

